package com.kfm.filter;

import com.kfm.util.Contains;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

//@WebFilter("/*")
public class LoginFilter implements Filter {

    private List<String> urls = new ArrayList<>();
    private List<String> suff = new ArrayList<>();

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // 只要是这些请求全部放行
        urls.add("/index.jsp"); // 登录页面
        urls.add("/login"); //get 登录页面  post 登录请求
        urls.add("/captcha"); // 验证码

        suff.add(".css");  // css 资源
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;

        // /files/xxx
        String requestURI = httpServletRequest.getRequestURI();

        // /xxx  将上下文路径替换
        String path = requestURI.replace(httpServletRequest.getContextPath(), "");

        // 是否不需要登录， false 表示登录才能访问
        boolean flag = false;

        // 如果属于 放行要求
        if (urls.contains(path)){
            flag = true;
        } else {
            for (String suf : suff){
                if (path.endsWith(suf)){
                    flag = true;
                    break;
                }
            }
        }

        if (flag){
            // 放行
            chain.doFilter(request, response);
        } else {
            // 需要登录才能访问资源
            HttpSession session = httpServletRequest.getSession();

            // 获取登录标识
            Object attribute = session.getAttribute(Contains.LOGIN_FLAG);


            if (attribute == null){
                // 未登录
                httpServletResponse.sendRedirect("login");
            }else{
                // 放行
                chain.doFilter(request, response);
            }
        }
    }
}
